package features.advance.jdk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.util.stream.IntStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author LIN
 * @date 2021-11-22 19:36
 */
public class ZipDemo {

    public static void main(String[] args) {
        Solution solution = new Solution() {
        };
//        String fileName = "D:\\project-2020\\qiming\\doc\\日志总结\\体温打卡\\";
        String fileName = ".\\";
        System.out.println(fileName);
        File file = new File(fileName);
        if(file.isDirectory()){
            File[] files = file.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return !name.contains(".zip") && !name.contains(".jar") && !name.contains(".bat");
                }
            });
            IntStream.range(0,files.length).forEach(i->{
                File f = files[i];
                String name = f.getAbsolutePath();
                try {
                    solution.zip(name+".zip",new File(name));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

    }

    public String getPath() {

        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

        if (System.getProperty("os.name").contains("dows")) {

            path = path.substring(1,path.length());

        }

        if (path.contains("jar")) {

            path = path.substring(0,path.lastIndexOf("."));

            return path.substring(0,path.lastIndexOf("/"));

        }

        return path.replace("target/classes/", "");

    }

    static class Solution {
        public void zip(String zipFileName,File inputFile) throws Exception {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
            zip(out,inputFile,"");
            out.close();
        }
        public void zip(ZipOutputStream out, File f, String base) throws Exception {
            if(f.isDirectory()){
                File[] fl = f.listFiles();
                out.putNextEntry(new ZipEntry(base+"/"));
                base = base.length() == 0 ? "":base+"/";
                for (int i = 0; i < fl.length; i++) {
                    zip(out,fl[i],fl[i].getName());
                }
            }else{
                out.putNextEntry(new ZipEntry(base));
                FileInputStream in = new FileInputStream(f);
                int b;
                while((b = in.read())!=-1){
                    out.write(b);
                }
                in.close();
            }
        }
    }
}
